<template>
	<SlotModal ref='slotModalRef' v-bind='slotModalConfig'>
		<n-form ref='formRef' v-bind='formConfig'
				:model='controlFormData' :rules='formRules'>
			<n-grid :x-gap='24' :cols='24'>
				<n-form-item-grid-item span='24' label='公告编号' path='noticeCode'>
					<n-input v-model:value='infoFormData.noticeCode' disabled/>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='24' label='公告标题' path='title'>
					<n-input v-model:value='infoFormData.title' disabled/>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='12' label='开始时间' path='startTime'>
					<n-date-picker v-model:formatted-value='controlFormData.startTime'
								   type='datetime' format='yyyy-MM-dd HH:mm:ss'
								   value-format='yyyy-MM-dd HH:mm:ss' clearable/>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='12' label='结束日期' path='endTime'>
					<n-date-picker v-model:formatted-value='controlFormData.endTime'
								   type='datetime' format='yyyy-MM-dd HH:mm:ss'
								   value-format='yyyy-MM-dd HH:mm:ss' clearable/>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='24' label='公告可见部门' path='deptList'
									   label-placement='top'>
					<n-transfer
						v-bind='deptGroupTransferConfig'
						v-model:value='controlFormData.deptList'
						:options='deptListOptions'/>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='24' label='公告可见角色' path='roleList'
									   label-placement='top'>
					<n-transfer
						v-bind='roleGroupTransferConfig'
						v-model:value='controlFormData.roleList'
						:options='roleListOptions'/>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='24' label='公告可见用户' path='userList'
									   label-placement='top'>
					<n-transfer
						v-bind='userGroupTransferConfig'
						v-model:value='controlFormData.userList'
						:options='userListOptions'/>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='12' label='是否热点' path='isHotSpot'>
					<n-switch v-model:value='controlFormData.isHotspot as boolean'
							  :checked-value='true' :unchecked-value='false'>
						<template v-slot:checked>是</template>
						<template v-slot:unchecked>否</template>
					</n-switch>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='12' label='是否启用' path='status'>
					<n-switch v-model:value='controlFormData.status as boolean'
							  :checked-value='true' :unchecked-value='false'>
						<template v-slot:checked>是</template>
						<template v-slot:unchecked>否</template>
					</n-switch>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='24'>
					<CKEditor-A4 ref='CKEditor5WatchDogRef'
								 v-model:htmlValue='htmlData'
								 readOnly :editorConfig='editorConfig'/>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='24' :show-feedback='false'>
					<n-flex justify='center' align='center'
							:wrap='false' inline style='width:100%;'>
						<n-button round secondary type='info'
								  @click='submitEvent'>
							提交
						</n-button>
						<n-button round secondary type='default'
								  @click='resetEvent'>
							重置
						</n-button>
					</n-flex>
				</n-form-item-grid-item>
			</n-grid>
		</n-form>
	</SlotModal>
</template>
<script lang='ts' setup>
import { defineAsyncComponent, onBeforeMount, onMounted, reactive, ref } from 'vue';
// axios
import axios from '@/config/axios/index.ts';
// 模态框和打印组件
import { VxeUI } from '@/config/vxe/index.ts';
import type { JsonResultProps } from '#/JsonResult.d.ts';
import { FormInst, FormProps, FormRules, FormValidationError, NTransfer, TransferProps } from 'naive-ui';
import type {
	SystemNoticeControlProps,
	SystemNoticeInfoProps, SystemNoticeProps
} from '#/src/components/page/systemManager/noticeMaintain/SystemNoticeProps.d.ts';
import { EditorConfig } from '@ckeditor/ckeditor5-core';
const SlotModal = defineAsyncComponent(() => import('@/components/customComponents/modal/SlotModal.vue'));
const CKEditorA4 = defineAsyncComponent(
	() => import('@/components/customComponents/CKEditor5WatchDog/CKEditor-A4.vue'));
// 接收的参数
const props = defineProps({
	reLoad : {
		type    : Function,
		require : true,
		default : null
	}
});
// --------------------------------------------------------------------------------
let currentData = reactive<Partial<SystemNoticeInfoProps>>({});
// --------------------------------------------------------------------------------
const slotModalConfig = reactive({
	reLoad            : () => props.reLoad(),
	onMountedEvent    : null,
	onOpenModalEvent  : () => onOpenModalEvent(),
	onCloseModalEvent : () => clearFormData(),
	onZoomModalEvent  : () => onZoomModalEvent(),
	resetEvent        : () => clearFormData()
});
// --------------------------------------------------------------------------------
const formConfig = reactive<FormProps>({
	labelWidth           : 'auto',
	labelAlign           : 'left',
	labelPlacement       : 'left',
	size                 : 'large',
	requireMarkPlacement : 'right-hanging'
});
const formRules = reactive<FormRules>({
	releaseDate   : {
		required : true,
		trigger  : ['input', 'blur'],
		message  : '请选择公告发布时间'
	},
	roleList      : {
		required : false,
		type     : 'array',
		trigger  : ['input', 'blur'],
		message  : '请从左侧勾选角色添加到右侧'
	},
	userList      : {
		required : false,
		type     : 'array',
		trigger  : ['input', 'blur'],
		message  : '请从左侧勾选用户添加到右侧'
	},
	releaseStatus : {
		required : true,
		type     : 'boolean',
		trigger  : ['input', 'blur'],
		message  : '请选择发布状态'
	},
	isHotSpot     : {
		required : true,
		type     : 'boolean',
		trigger  : ['input', 'blur'],
		message  : '请选择是否热点'
	},
	isEnable      : {
		required : true,
		type     : 'boolean',
		trigger  : ['input', 'blur'],
		message  : '请选择是否启用公告'
	}
});
// --------------------------------------------------------------------------------
const infoFormData = reactive<Partial<SystemNoticeInfoProps>>({});
const controlFormData = reactive<Partial<SystemNoticeControlProps>>({});
// --------------------------------------------------------------------------------
const editorConfig: EditorConfig = reactive({
	language : 'zh-cn',
	heading  : {
		options : [
			{ model : 'paragraph', title : 'Paragraph', class : 'ck-heading_paragraph' },
			{ model : 'heading1', view : 'h1', title : 'Heading 1', class : 'ck-heading_heading1' },
			{ model : 'heading2', view : 'h2', title : 'Heading 2', class : 'ck-heading_heading2' },
			{ model : 'heading3', view : 'h3', title : 'Heading 3', class : 'ck-heading_heading3' }
		]
	}
});
const htmlData = ref<string>('');
// --------------------------------------------------------------------------------
const deptGroupTransferConfig = reactive<TransferProps>({
	size             : 'large',
	sourceTitle      : '搜索并选择部门',
	targetTitle      : '已选部门',
	sourceFilterable : true,
	targetFilterable : true,
	virtualScroll    : true
});
const roleGroupTransferConfig = reactive<TransferProps>({
	size             : 'large',
	sourceTitle      : '搜索并选择角色',
	targetTitle      : '已选角色',
	sourceFilterable : true,
	targetFilterable : true,
	virtualScroll    : true
});
const userGroupTransferConfig = reactive<TransferProps>({
	size             : 'large',
	sourceTitle      : '搜索并选择用户',
	targetTitle      : '已选用户',
	sourceFilterable : true,
	targetFilterable : true,
	virtualScroll    : true
});
const deptListOptions = reactive([]);
const roleListOptions = reactive([]);
const userListOptions = reactive([]);
// --------------------------------------------------------------------------------
const slotModalRef = ref<InstanceType<typeof SlotModal>>();
const formRef = ref<FormInst>();
const CKEditor5WatchDogRef = ref<InstanceType<typeof CKEditorA4>>();
onBeforeMount(async () => {
	/*await initOptions();*/
});
onMounted(async () => {
});
const initOptions = async () => {
	Promise.all([
		axios.get('/role/options'),
		axios.get('/user/options')
	]).then((jsonResult: Array<any>) => {
		const jsonResult1 = jsonResult[0];
		const jsonResult2 = jsonResult[1];
		if (jsonResult1.status && jsonResult2.status) {
			Object.assign(roleListOptions, jsonResult1.data);
			Object.assign(userListOptions, jsonResult2.data);
		} else {
			VxeUI.modal.message({
				content : `${jsonResult1.msg}\n${jsonResult2.msg}`,
				status  : 'warning',
				id      : 'failedMessage'
			});
		}
	}).catch((error: unknown) => {
		console.error(error);
		VxeUI.modal.message({
			content : '系统异常,请稍后再试',
			status  : 'error',
			id      : 'errorMessage'
		});
	});
};
const showModal = async (rowData: SystemNoticeProps) => {
	currentData.noticeCode = rowData.noticeCode;
	await slotModalRef.value!.openModal({
		height     : '500',
		width      : '700',
		title      : '公告发布信息',
		showClose  : true,
		showZoom   : true,
		fullscreen : false
	});
};
const onOpenModalEvent = async () => {
	return new Promise((resolve, reject): void => {
		Promise.all([
			axios.post(`/notice/detail/${sessionStorage.getItem('loginTenantCode')}/${currentData.noticeCode}`),
			axios.post(`/notice/controlDetail/${sessionStorage.getItem('loginTenantCode')}/${currentData.noticeCode}`)
		]).then((jsonResult: Array<any>) => {
			const jsonResult1 = jsonResult[0];
			const jsonResult2 = jsonResult[1];
			if (jsonResult1.status && jsonResult2.status) {
				Object.assign(infoFormData, {
					id          : jsonResult1.data.id,
					title       : jsonResult1.data.title,
					htmlContent : jsonResult1.data.htmlContent
				});
				if (jsonResult2.data) {
					// 修改控制信息
					Object.assign(controlFormData, {
						id            : jsonResult1.data.id,
						noticeId      : jsonResult2.data.noticeId,
						releaseDate   : jsonResult2.data.releaseDate,
						endDate       : jsonResult2.data.endDate,
						roleList      : jsonResult2.data.roleList,
						userList      : jsonResult2.data.userList,
						releaseStatus : jsonResult2.data.releaseStatus,
						isHotSpot     : jsonResult2.data.isHotSpot,
						isEnable      : jsonResult2.data.isEnable,
						releaseUser   : jsonResult2.data.releaseUser
					});
				} else {
					// 新增的控制信息
					Object.assign(controlFormData, {
						noticeId      : jsonResult1.data.id,
						releaseUser   : jsonResult2.data.releaseUser,
						releaseDate   : jsonResult2.data.releaseDate,
						endDate       : jsonResult2.data.endDate,
						roleList      : [],
						userList      : [],
						releaseStatus : false,
						isHotSpot     : false,
						isEnable      : false
					});
				}
				resolve(null);
			} else {
				VxeUI.modal.message({
					content : `${jsonResult1.msg}\n${jsonResult2.msg}`,
					status  : 'warning',
					id      : 'failedMessage'
				});
				reject();
			}
		}).catch((error: unknown) => {
			console.error(error);
			VxeUI.modal.message({
				content : '系统异常,请稍后再试',
				status  : 'error',
				id      : 'errorMessage'
			});
			reject();
		});
	});
};
const onZoomModalEvent = async () => {
	console.log('onZoomModalEvent');
};
const clearFormData = async () => {
	Object.assign(currentData, {});
	Object.assign(htmlData, '');
	Object.assign(infoFormData, {
		id          : null,
		title       : null,
		htmlContent : null
	});
	// 清理表单数据
	Object.assign(controlFormData, {
		id            : null,
		noticeId      : null,
		releaseUser   : null,
		releaseDate   : null,
		endDate       : null,
		roleList      : null,
		userList      : null,
		releaseStatus : null,
		isHotSpot     : null,
		isEnable      : null
	});
	// 去除表单校验提示
	formRef.value?.restoreValidation();
};
const submitEvent = async () => {
	// 校验菜单
	formRef.value?.validate((errors?: Array<FormValidationError>): void => {
		if (errors) {
			VxeUI.modal.message({ content : '请先完善填写的内容!', status : 'warning', id : 'validateMessage' });
		} else {
			// 提交数据
			axios<any, JsonResultProps<any>, any>({
				method : 'POST',
				url    : '/notice/publish',
				data   : controlFormData
			}).then((jsonResult: JsonResultProps<any>) => {
				if (jsonResult['status']) {
					// 提示用户
					VxeUI.modal.message({
						content : jsonResult['msg'],
						status  : 'success',
						id      : 'successMessage'
					});
					// 刷新数据
					props.reLoad(null);
					slotModalRef.value!.closeModal();
				} else {
					VxeUI.modal.message({
						content : jsonResult['msg'],
						status  : 'warning',
						id      : 'failedMessage'
					});
				}
			}).catch((error: unknown) => {
				console.error(error);
				VxeUI.modal.message({
					content : '系统异常,请稍后再试',
					status  : 'error',
					id      : 'errorMessage'
				});
			});
		}
	});
};
const resetEvent = async () => {
	// 清理表单数据
	Object.assign(controlFormData, {
		releaseUser   : null,
		releaseDate   : null,
		endDate       : null,
		roleList      : null,
		userList      : null,
		releaseStatus : null,
		isHotSpot     : null,
		isEnable      : null
	});
	// 去除表单校验提示
	formRef.value?.restoreValidation();
};
// 导出方法
defineExpose({ showModal });
</script>